import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/login/login_bean/login_search_organization_bean.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_widget_lib.dart';

class LoginViewModel extends BaseViewModel {
  ///发送验证码
  static const String SEND_SMS_CODE_API =
     ServerApi.BASE_URL + "/sms/sendValidationCode";

  ///获取该账号所属机构
  static const String SEARCH_ORGANIZATION_API =
     ServerApi.BASE_URL + "/app/searchOrganization";

  ///注销账号
  static const String USER_LOG_OFF =
     ServerApi.BASE_URL + "/app/appUserLogoff";

  LoginViewModel(BaseState<StatefulWidget> state) : super(state);

  ///发送短信验证码
  void sendSmsCode(
      BuildContext context, String phone, VoidCallback jumpToAuthFunc) {
    if (phone == null || phone == "") {
      return;
    }
    if(phone.length != DEFAULT_PHONE_LENGTH_LIMIT){
      return;
    }
    VgHudUtils.show(context,"获取验证码");
    VgHttpUtils.get(SEND_SMS_CODE_API,
        params: {
          "phone": globalSubPhone(phone) ?? "",
          "come": "app",
        },
        callback: BaseCallback(onSuccess: (val) {
          VgHudUtils.hide(context);
          if (jumpToAuthFunc != null) {
            jumpToAuthFunc();
          }
        }, onError: (msg) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }));
  }

  ///获取该账号一起学机构
  void searchOrganization(
      BuildContext context, String phone,BaseCallback callback) {
    if (phone == null || phone == "") {
      return;
    }
    if(phone.length != DEFAULT_PHONE_LENGTH_LIMIT){
      return;
    }
    loading(false);
    VgHttpUtils.get(SEARCH_ORGANIZATION_API,
        params: {
          "phone": globalSubPhone(phone) ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          callback?.onSuccess?.call(val);
        }, onError: (msg) {
          callback?.onError(msg);
        }));
  }

  ///注销账号
  void userLogOff(
      BuildContext context, VoidCallback callback) {
    loading(true);
    VgHttpUtils.post(USER_LOG_OFF,
        params: {
          "authId": UserRepository.getInstance().authId??"",
        },
        callback: BaseCallback(onSuccess: (val) {
          loading(false);
          callback?.call();
        }, onError: (msg) {
          loading(false);
          VgToastUtils.toast(context, msg);
        }));
  }

}
